package org.zxp.classload;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @program: effectiveJava
 * @description:测试同一个类不同类加载器
 * @author: X-Pacific zhang
 * @create: 2019-07-02 17:10
 **/
public class ClassLoaderTest {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Test obj1 = new Test();
        ClassLoader myclassloader = new ClassLoader(){
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                try{
                    String fileName = "file:/D:/beatyWork/learnwork/effectiveJava/target/classes/org/zxp/classload/Test.class";
                    byte[] cLassBytes = null;
                    Path path = null;
                    try {
                        path = Paths.get(new URI(fileName));
                        cLassBytes = Files.readAllBytes(path);
                    } catch (IOException | URISyntaxException e) {
                        e.printStackTrace();
                    }
                    return defineClass(name, cLassBytes, 0, cLassBytes.length);
                }catch(Exception e){
//                    e.printStackTrace();
                    return super.loadClass(name);
                }
            }
        };
        Class clazz = myclassloader.loadClass("org.zxp.classload.Test");
//        System.out.println(obj2 instanceof ClassLoaderTest);
        System.out.println(clazz == Test.class);//false

        Object obj = clazz.newInstance();
        System.out.println(obj.getClass() == Test.class);//false
    }
}
